import React,{useEffect, useState} from 'react'
import Taro,{useDidShow} from '@tarojs/taro'
import { AtIndexes } from 'taro-ui'
import {View,Image,Text} from '@tarojs/components'
import currentEnv from '../../../configure/currentEnv'
import './index.scss'
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/indexes.scss";
import "taro-ui/dist/style/components/list.scss";

export default function SelectCity() {
  const [cityInfo,setCityInfo] = useState({})
  const [position,setPosition] = useState({})
  const [list,setList] = useState([])
  const [type,setType] = useState('')
  useEffect(()=>{
    const {router} = Taro.getCurrentInstance()
    setType(router.params?.type)
    Taro.showLoading({title:'加载中...'})
    Taro.$get('/cinema-app/api/v1/district/listV2','','1').then(res=>{
      if(res.code == '1' && res.content?.length){
        let groupedCities = res.content.reduce((acc, city) => {
          let firstLetter = city.pinyin.charAt(0).toUpperCase();
          if (!acc[firstLetter]) {
            acc[firstLetter] = [];
          }
          acc[firstLetter].push({...city, name: city.cityName});
          return acc;
        }, {});
      
        let result = Object.keys(groupedCities).sort().map(key => {
          return {
            title: key,
            key: key,
            items: groupedCities[key]
          };
        });
        setList(result)
        Taro.hideLoading()
      }
    })
    setPosition(Taro.getStorageSync('position'))
    Taro.eventCenter.on('updateLocation',e=>{
      setPosition(Taro.getStorageSync('position'))
    })
    return ()=>{ Taro.eventCenter.off('updateLocation') }
  },[])
  useDidShow(()=>{
    const {router} = Taro.getCurrentInstance()
    let loca = Taro.getStorageSync('cityInfo')
    if(router.params?.type == 'ticket'){
      loca = Taro.getStorageSync('ticketCity') || Taro.getStorageSync('cityInfo')
    }
    if(loca && loca.name){
      setCityInfo(loca || {})
    }
  })
  
  const handleSelectCity =e=>{
    if(type == 'ticket'){
      Taro.setStorageSync('ticketCity',e)
    }else{
      Taro.setStorageSync('cityInfo',e)
    }
    Taro.navigateBack().catch(()=>{
      Taro.reLaunch({
        url:currentEnv.project=='yingjing'?'/pages/index/index':'/pages/movie/index'
      })
    })
  }
  let fn = ''
  return (
    <View className='select-city' style={{ height: "100vh" }}>
      <AtIndexes list={list} onClick={e=>{handleSelectCity(e)}} topKey="定位" isVibrate={false} animation={true} isShowToast={false}>
        <View className="city-header">
          {position?.name?<>
            <View className="city-title">定位城市</View>
            <View className="header-item" onClick={()=>{
              if(type == 'ticket'){
                Taro.setStorageSync('ticketCity',position)
              }else{
                Taro.setStorageSync('cityInfo',position)
              }
              Taro.navigateBack().catch(()=>{
                Taro.reLaunch({
                  url:currentEnv.project=='yingjing'?'/pages/index/index':'/pages/movie/index'
                })
              })
            }}><Image src={require('@/images/home/location.svg')} mode='widthFix' style={{width:'16px',height:'16px',marginRight:'4px'}} />{position?.name}</View>
          </>:null}
          <View className="city-title">当前城市</View>
          {cityInfo?.name?<View className="header-item active">{cityInfo.name}</View>:null}
        </View>
      </AtIndexes>
    </View>
  )
}
